<template lang="">
  <li>
    <!-- 标题 -->
    <div
      :class="{ bold: isFolder }"
      @click="isOpen = !isOpen"
      @dblclick="changeType"
    >
      {{ model.name }}
      <!-- 开关 -->
      <span v-if="isFolder">[{{ isOpen ? "-" : "+" }}]</span>
    </div>
    <!-- 展示子节点 -->
    <ul v-if="isFolder" v-show="isOpen">
      <TreeItem
        class="tree-item"
        v-for="model in model.children"
        :model="model"
      ></TreeItem>
      <li class="add" @click="addChildren">+</li>
    </ul>
  </li>
</template>
<script setup>
import { ref, computed } from "vue";

// 定义Props
const props = defineProps({
  model: Object,
});
// 计算当前组件有没有子节点，是不是打开的状态
const isOpen = ref(false);
const isFolder = computed(
  () => props.model.children && props.model.children.length
);

// 定义变更函数
function addChildren() {
  props.model.children.push({ name: "newItem" });
}

function changeType() {
  // 把节点变成目录，增加一个子节点，打开状态
  if (!isFolder.value) {
    props.model.children = [];
    addChildren();
    isOpen.value = true;
  }
}
</script>
<style></style>
